<template>
  <div class="table-page">
    <div class="flex flex-a-c overflow-x-auto">
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEDF0 mr-20 round-6 mb-20 nowrap">
        用户数量： {{ amountData.userCount }}
      </div>
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEDF0 mr-20 round-6 mb-20 nowrap">
        设备数量： {{ amountData.deviceCount }}
      </div>
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgECFAF2 mr-20 round-6 mb-20 nowrap">
        在线设备数量： <span class="text43cf7c">{{ amountData.deviceOnlineCount }}</span>
      </div>
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgF2F2F2 mr-20 round-6 mb-20 nowrap">
        离线设备数量： <span class="texta6a6a6">{{ amountData.deviceOfflineCount }}</span>
      </div>
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgF2F2F2 mr-20 round-6 mb-20 nowrap">
        未绑定设备： <span class="texta6a6a6">{{ amountData.deviceNoUsedCount }}</span>
      </div>
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEBEF mr-20 round-6 mb-20 nowrap">
        设备异常数量： <span class="textff0000">{{ amountData.deviceExceptionalCount }}</span>
      </div>
      <div class="h-10n flex-center mb-20 nowrap" v-if="renew">
        <a-button type="text" size="small" :loading="previewDataLoading" @click="getPreviewData(true)">
          <template #icon>
            <icon-loop />
          </template>
          上次更新时间：{{ renew }}
        </a-button>
      </div>
    </div>
    <a-form label-align="right" auto-label-width layout="inline" :model="listParams" size="small" class="form my-10">
      <a-form-item field="sourceChatRoomId" hide-label>
        <a-select
          v-model="listParams.sourceChatRoomId"
          class="w-70n"
          placeholder="选择跟发源头群筛选"
          @change="changeCurrent(1)"
        >
          <a-option value="" label="全部源头群"></a-option>
          <a-option
            v-for="item in sourceList"
            :key="item.sourceChatRoomId"
            :value="item.sourceChatRoomId"
            :label="item.name"
          ></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="searchKeyword" hide-label>
        <a-input
          class="w-50n"
          v-model="listParams.searchKeyword"
          placeholder="输入微信昵称/微信名筛选"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>
      <a-form-item field="inviteCode" hide-label>
        <a-input
          class="w-40n"
          v-model="listParams.inviteCode"
          placeholder="输入用户邀请码筛选"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>
      <a-form-item field="address" hide-label>
        <a-input
          class="w-40n"
          v-model="listParams.address"
          placeholder="输入地址模糊搜索"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>
      <a-form-item field="isMultipleAccounts" label="是否多账户">
        <a-radio-group v-model="listParams.isMultipleAccounts" @change="changeCurrent(1)">
          <a-radio value="">全部</a-radio>
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item field="userWechatNoBegin" label="账号批次" v-if="listParams.isMultipleAccounts == 1">
        <a-input-group compact>
          <a-input-number v-model="listParams.userWechatNoBegin" :min="1" class="w-30n" placeholder="批次起始值" />
          <a-input style="width: 40px; pointer-events: none" placeholder="~" disabled />
          <a-input-number v-model="listParams.userWechatNoEnd" :min="1" class="w-30n" placeholder="批次结束值" />
        </a-input-group>
      </a-form-item>
      <a-form-item hide-label>
        <a-space>
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="key"
      id="equipmentList"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :stripe="false"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      :pagination="pagination"
      @refresh="getTableData"
      v-model:selectedKeys="selectedKeys"
      :row-class="customRow"
      @filter-change="statusChange"
      @sorter-change="onSorterChange"
    >
      <template #custom-extra>
        <a-button type="primary" v-if="selectedKeys.length" size="small" @click="compensate(selectedKeys)">
          <template #icon><icon-clock-circle /></template>
          <span>批量补偿时长</span>
        </a-button>
        <div class="aggs flex px-10 flex-a-c pl-10 font-bold text-size-14 mr-10 text-overflow-1">
          共查询到
          <span>{{ amountDataWidthParams.deviceNum }}</span> 个设备（{{
            amountDataWidthParams.userNum
          }}个用户），在线设备 {{ amountDataWidthParams.onlineNum }} 个，离线设备
          {{ amountDataWidthParams.offlineNum }} 个，异常掉线设备
          {{ amountDataWidthParams.exceptionalOfflineNum }} 个，跟发源头群设备
          {{ amountDataWidthParams.followGroupOnlineNum }} 个，跟圈设备
          {{ amountDataWidthParams.followMomentOnlineNum }} 个
        </div>
      </template>
      <template #info="{ record }">
        <div class="flex flex-a-c">
          <ImgHoverPreview :url="record?.wxInfo?.vcHeadImgUrl" round="50%" />
          <div class="ml-8">
            <div>{{ record?.wxInfo?.vcNickName || '--' }}</div>
            <div class="text-size-12">{{ record?.wxInfo?.vcRobotWxId || '--' }}</div>
          </div>
        </div>
      </template>
      <template #residue="{ record }">
        <template v-if="!record.expiresAt">
          <span>--</span>
        </template>
        <template v-else>
          <a-countdown
            :value="new Date(record.expiresAt).getTime()"
            :now="Date.now()"
            format="D天HH:mm:ss"
            :value-style="{ fontSize: '14px' }"
          />
        </template>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onDetail(record.userWechatId)"> 详情 </a-button>
        <a-button type="text" size="small" @click="onAdd(record.userId)"> 新增设备 </a-button>
        <a-button type="text" size="small" @click="compensate([record.key])"> 补偿时长 </a-button>
      </template>
    </GiTable>
    <EditDrawer ref="EditDrawerRef" @getTableData="getTableData" @restore="selectedKeys = []" :record="record" />
    <a-modal v-model:visible="deviceVisible" title="新增设备" @before-ok="onAddDevice">
      <a-form ref="formRef" size="medium" :model="deviceParam" auto-label-width>
        <a-form-item label="所属用户ID" field="userId">
          <a-input disabled v-model="deviceParam.userId"></a-input>
        </a-form-item>
        <a-form-item label="到期时间" field="days">
          <a-input-group>
            <a-select
              :style="{ width: 'fit-content' }"
              :trigger-props="{ autoFitPopupMinWidth: true }"
              v-model="daysType"
              @change="getTopData"
            >
              <a-option :value="1" label="按日期" />
              <a-option :value="2" label="按天数" />
            </a-select>
            <template v-if="daysType == 1">
              <a-date-picker
                v-model="date"
                show-time
                :time-picker-props="{ defaultValue: '23:59:59' }"
                :disabledDate="(current) => dayjs(current).isBefore(dayjs().startOf('date'))"
              >
                <a-input :model-value="date || '请选择日期'"></a-input>
              </a-date-picker>
            </template>
            <template v-else>
              <a-input-number v-model="deviceParam.days" :min="1"></a-input-number>
            </template>
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { usePagination } from '@/hooks'
import { useSource } from '@/hooks/app'
import { equipmentStatistics, equipmentList, equipmentListStatistics, accountAddUserWechat } from '@/apis'
import { deleteEmpty, reAssign } from '@/utils/common'
import GiDot from '@/components/GiDot/index.vue'
import { Message } from '@arco-design/web-vue'
import { statusArr } from '../data'
import EditDrawer from './EditDrawer.vue'
import dayjs from 'dayjs'

defineOptions({ name: 'equipmentList' })

const router = useRouter()

const columns = ref([
  {
    title: '设备（微信）信息',
    width: 150,
    slotName: 'info'
  },
  {
    title: '用户邀请码',
    width: 110,
    align: 'center',
    render(data) {
      const text = data.record.inviteCode
      return text || '--'
    }
  },
  {
    title: '用户ID',
    width: 110,
    align: 'center',
    render(data) {
      const text = data.record.userId
      return text || '--'
    }
  },
  {
    title: '设备数\n开通/在线',
    width: 100,
    align: 'center',
    dataIndex: 'openOnlineNum'
  },
  {
    title: '开通与到期',
    width: 180,
    align: 'center',
    dataIndex: 'createdExpiresAt'
  },
  {
    title: '剩余时长',
    width: 150,
    align: 'center',
    slotName: 'residue',
    sortable: {
      sortDirections: ['ascend', 'descend'],
      sorter: true
    }
  },
  {
    title: '所属城市',
    width: 110,
    align: 'address',
    render(data) {
      const text = data.record.address
      return text || '--'
    }
  },
  {
    title: '跟发数据',
    width: 150,
    align: 'center',
    dataIndex: 'followStatus',
    filterable: {
      filters: [
        {
          text: '全部',
          value: 1
        },
        {
          text: '只跟群',
          value: 2
        },
        {
          text: '只跟圈',
          value: 3
        },
        {
          text: '无',
          value: 4
        }
      ]
    },
    render: ({ record }) => {
      return record.followGroupMoment
    }
  },
  {
    title: '设备状态',
    width: 120,
    dataIndex: 'deviceStatus',
    align: 'center',
    filterable: {
      filters: [
        {
          text: '在线',
          value: 1
        },
        {
          text: '主动离线',
          value: 0
        },
        {
          text: '到期离线',
          value: 10
        },
        {
          text: '异常掉线',
          value: 11
        },
        {
          text: '未绑定',
          value: 12
        }
      ]
    },
    render: (data) => {
      const status = data.record.status
      const type = statusArr[status] ? statusArr[status].type : 'info'
      const text = statusArr[status] ? statusArr[status].desc : '未知'
      return h(GiDot, {
        animation: false,
        type: type,
        text: `${text} （${data.record.supplierId == 1 ? '果冻' : 'eco'}）`
      })
    }
  },
  {
    title: '操作',
    width: 200,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])

const loading = ref(false)
const previewDataLoading = ref(false)
const EditDrawerRef = ref()
const deviceVisible = ref(false)
const selectedKeys = ref([])
const renew = ref('')
const tableData = ref([])
const formRef = ref()
const date = ref()
const daysType = ref(1)
const amountData = ref({
  userCount: 0, //用户数量
  deviceCount: 0, //设备数量
  deviceOnlineCount: 0, //在线设备数量
  deviceOfflineCount: 0, //离线设备数量
  deviceNoUsedCount: 0, //未绑定设备
  deviceExceptionalCount: 0 //设备异常数量
})
const amountDataWidthParams = reactive({
  deviceNum: 0, //设备总数量
  onlineNum: 0, //在线设备数量
  offlineNum: 0, //离线设备数量
  userNum: 0, //用户数
  exceptionalOfflineNum: 0, //异常设备数量
  followGroupOnlineNum: 0, //跟群设备数量
  followMomentOnlineNum: 0 //跟圈设备数量
})
const listParams = reactive({
  deviceStatus: undefined,
  followStatus: undefined,
  sourceChatRoomId: undefined,
  searchKeyword: undefined,
  expiresAtSort: undefined,
  isMultipleAccounts: undefined,
  userWechatNoBegin: undefined,
  userWechatNoEnd: undefined,
  inviteCode: undefined,
  address: undefined
})
const deviceParam = reactive({
  userId: undefined,
  days: undefined
})
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 10 })

const { sourceList, getSourceList } = useSource()
getSourceList()

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    const res = await equipmentList(deleteEmpty(listParams))
    tableData.value = res.data.list.map((item) => {
      const expiresAt = item.createdExpiresAt.split('\n')[1]
      return {
        ...item,
        key: `${item.userWechatId}☆${expiresAt}`
      }
    })
    setTotal(res?.data?.meta?.pagination?.total || 0)
    getPreviewDataWidthParams()
  } finally {
    loading.value = false
  }
}

const getPreviewData = async (tip = false) => {
  getTableData()
  try {
    previewDataLoading.value = true
    const res = await equipmentStatistics()
    amountData.value = res.data
    renew.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
    if (tip) {
      Message.success('刷新成功')
    }
  } finally {
    previewDataLoading.value = false
  }
}
getPreviewData(false)

const getPreviewDataWidthParams = async () => {
  const res = await equipmentListStatistics(deleteEmpty(listParams))
  reAssign(amountDataWidthParams, res.data)
}

const customRow = (record) => {
  const color = record.raw.color
  return color == '#ffffff' ? 'otherRow' : 'offRow'
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  listParams.expiresAtSort = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  changeCurrent(1)
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.deviceStatus =
    listParams.followStatus =
    listParams.sourceChatRoomId =
    listParams.searchKeyword =
    listParams.isMultipleAccounts =
    listParams.userWechatNoBegin =
    listParams.userWechatNoEnd =
    listParams.inviteCode =
    listParams.address =
      undefined
  changeCurrent(1)
}

// 补偿时长
const compensate = (keys) => {
  if (keys.length) {
    EditDrawerRef?.value.compensate(keys)
  }
}

// 点击新增
const onAdd = (id) => {
  deviceParam.userId = id
  deviceVisible.value = true
}

// 新增设备
const onAddDevice = async () => {
  if (daysType.value == 1 && !date.value) {
    Message.error('请选择日期')
    return false
  }
  if (daysType.value == 2 && !deviceParam.days) {
    Message.error('请输入天数')
    return false
  }
  if (daysType.value == 1) {
    let diffDay = dayjs(date.value).diff(dayjs(), 'day') + 1
    if (diffDay <= 0) diffDay = 1
    deviceParam.days = diffDay
  }
  await accountAddUserWechat(deviceParam)
  Message.success('开通成功')
  deviceParam.days = deviceParam.userId = undefined
  deviceVisible.value = false
  getTableData()
  return true
}

// 列表筛选-状态
const statusChange = (dataIndex, filteredValues) => {
  listParams[dataIndex] = filteredValues.length ? filteredValues[0] : undefined
  changeCurrent(1)
}

// 跳转详情
const onDetail = (userWechatIdO) => {
  router.push({ path: '/equipment/equipmentDetail', query: { userWechatIdO } })
}
</script>

<style lang="scss" scoped>
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  :deep(.arco-table-th-title) {
    font-weight: bold;
  }
  :deep(.offRow .arco-table-td) {
    background: rgba(241, 241, 241, 0.4);
  }
  :deep(.errorRow .arco-table-td) {
    background: #f1f1f1;
    color: #d63f3f !important;
  }
  :deep(.errorRow .arco-statistic-value) {
    color: #d63f3f !important;
  }
  .form {
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
}
.bgFCEDF0 {
  background-color: #fcedf0;
}
.bgFCEDF0 {
  background-color: #fcedf0;
}
.bgECFAF2 {
  background-color: #ecfaf2;
}
.bgF2F2F2 {
  background-color: #f2f2f2;
}
.bgFCEBEF {
  background-color: #fcebef;
}
.text43cf7c {
  color: #43cf7c;
}
.texta6a6a6 {
  color: #a6a6a6;
}
.textff0000 {
  color: #ff0000;
}

.aggs {
  width: fit-content;
  height: 26px;
  background-color: rgba(227, 60, 100, 0.1);
  border-radius: 6px;
  border: 1px solid rgb(255, 50, 114);
}
</style>
